package com.example.manager;

import android.os.Handler;
import android.os.Looper;

import com.example.model.Block;
import com.example.utils.Constants;
import com.example.view.GameView;
import com.example.view.PreviewView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.logging.LogRecord;

public class GameCenter {
    //内部提供一个静态的共享属性对象
    public static final GameCenter defaultCenter = new GameCenter();
    private PreviewView mpreviewView;
    private GameView mGameView;
    private int row = Constants.ROW;
    private int column = Constants.COLUMN;
    public int[][] boards;


    private final Handler mHandler = new Handler(Looper.getMainLooper());
    private final Runnable mMoveDownTask = new Runnable() {
        @Override
        public void run() {
            moveDown();
            mHandler.postDelayed(this,1000);
        }
    };

    public void startAutoMoveDown(){

            mHandler.post(mMoveDownTask);

    }

    /*为了让在顶部出现的方块真正的居中显示，
    我们需要去GameView中得到真正的游戏界面的宽高，
    并在点击开始游戏之后把值传给它，所以定义一个setBoardSize函数是为了接受到真正宽高的值*/

    public void setBoardSize(int row, int column){
        this.row = row;
        this.column = column;
        this.boards = new int[row][column];

        BlockManager.defaultManager.resetPosition(row, column);
        mGameView.refresh();
    }


    private GameCenter(){

    }

    //让GameCenter绑定预览游戏视图
    public void bingView(PreviewView previewView, GameView gameView) {
        this.mpreviewView = previewView;
        this.mGameView = gameView;
    }

    //开始游戏
    public void start() {
        showNext();
    }

    public void moveLeft() {
        BlockManager.defaultManager.getCurrentBlock().reduceColumn();
        if(isCollision()){
            BlockManager.defaultManager.getCurrentBlock().addColumn();
        }
        mGameView.refresh();
    }

    public void moveRight() {
        BlockManager.defaultManager.getCurrentBlock().addColumn();
        if(isCollision()){
            BlockManager.defaultManager.getCurrentBlock().reduceColumn();
        }
        mGameView.refresh();
    }



    private void showNext(){
        //获取预览方块
        Block previewBlock = BlockManager.defaultManager.getPreviewBlock(0,column / 2 - 1);

        //给预览视图显示
        mpreviewView.showBlock(previewBlock);

        mGameView.refresh();
    }

    private void mergeBlock(){
        Block block = BlockManager.defaultManager.getCurrentBlock();
        int[][] shapes = block.getShape();
        int x;
        int y;
        for (int i = 0; i < shapes.length; i++) {
            for (int j = 0; j < shapes[0].length; j++) {
                if (shapes[i][j] == 1){
                    x = block.column + j;
                    y = block.row + i;
                    boards[y][x] = 1;
                }
            }
        }
        clearCompleteLines();
    }

    private void clearCompleteLines() {
        List<Integer> completedLines = new ArrayList<>();

        for (int row = 0; row < boards.length; row++) {
            boolean full = true;
            for (int col = 0; col < boards[0].length; col++) {
                if (boards[row][col] == 0) {
                    full = false;
                    break;
                }
            }
            if (full) {
                completedLines.add(row); // 记录需要消除的行号

            }
        }

        // 执行消行（从下往上处理）
        for (int line : completedLines) {
            // 将上方所有行下移一行
            for (int y = line; y > 0; y--) {
                System.arraycopy(boards[y-1], 0, boards[y], 0, boards[0].length);
            }
            // 清空最顶层
            Arrays.fill(boards[0], 0);
        }
    }


    public void moveDown() {
        BlockManager.defaultManager.getCurrentBlock().addRow();
        if(isCollision()) {
            BlockManager.defaultManager.getCurrentBlock().reduceRow();
            // 触底即可合并当前方块
            mergeBlock();
            showNext();
        }
        if (mGameView != null) {
            mGameView.refresh();
        }
    }


    public void rotate() {
        BlockManager.defaultManager.getCurrentBlock().rotate();
        if (isCollision()){
            for (int i = 0; i < 3; i++) {
                BlockManager.defaultManager.getCurrentBlock().rotate();
            }
        }
        mGameView.refresh();
    }

    private boolean isCollision(){
        Block block = BlockManager.defaultManager.getCurrentBlock();
        int[][] shapes = block.getShape();
        for (int i = 0; i < shapes.length; i++) {
            for (int j = 0; j < shapes[0].length; j++) {
                if (shapes[i][j] == 1){
                    if (block.column + j < 0 || block.column + j >= column || block.row + i >= row){
                        return true;
                    }

                    int x = i + block.row;
                    int y = j + block.column;

                    if (boards[x][y] == 1){
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
